package com.desay.pangoo.itmt.repository.rag;

import com.desay.pangoo.itmt.entity.rag.MessageEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;


/**
 * @author uids1175
 */
@Repository
public interface MessageEntityRepository extends JpaSpecificationExecutor<MessageEntity>, PagingAndSortingRepository<MessageEntity, Long> {

    List<MessageEntity> findAllByChatId(Long chatId);

    MessageEntity findByMessageId(Long messageId);

    long countByChatId(Long chatId);

    @Modifying
    @Query("UPDATE MessageEntity m SET m.deleted = 1 WHERE m.chatId = :chatId")
    void deleteByChatId(@Param("chatId") Long chatId);

    @Modifying
    @Query("UPDATE MessageEntity m SET m.deleted = 1 WHERE m.messageId = :messageId")
    void deleteByMessageId(@Param("messageId") Long messageId);

    @Query("SELECT m FROM MessageEntity m WHERE m.chatId = chatId AND m.role = role AND m.messageId > messageId")
    List<MessageEntity> findAllByChatIdAndRoleAndMessageIdGreaterThan(@Param("chatId") Long chatId, @Param("role") String role,@Param("messageId") Long messageId);

    @Modifying
    @Query("UPDATE MessageEntity m SET m.deleted = 1 WHERE m.parentId = :parentId")
    void deleteByParentId(@Param("parentId") Long parentId);
}
